package cn.peng.stu4teach.pages.home.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;
import java.util.List;

import cn.peng.stu4teach.R;
import cn.peng.stu4teach.databinding.ItemMsgTypeBinding;
import cn.peng.stu4teach.pages.home.bean.MsgTypeBean;
import cn.peng.stu4teach.util.webview.WebViewActivity;

/**
 * 功用：消息类型 列表使用的适配器
 */
public class MsgTypeAdapter extends RecyclerView.Adapter<MsgTypeAdapter.MsgTypeVh> {
    private List<MsgTypeBean> items = new ArrayList<>();

    /**
     * 设置数据并刷新视图
     */
    public void setItems (List<MsgTypeBean> pItems) {
        items = pItems;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MsgTypeVh onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ItemMsgTypeBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_msg_type, parent, false);

        return new MsgTypeVh(binding);
    }

    @Override
    public void onBindViewHolder (@NonNull MsgTypeVh holder, int position) {
        if (null == holder.binding || position > items.size()) {
            // 避免空指针和索引越界
            return;
        }

        MsgTypeBean item = items.get(position);
        holder.binding.setItem(item);
        holder.binding.getRoot().setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View v) {
                // TODO: 条目被点击了
                WebViewActivity.start(v.getContext(),item.name,"https://developer.android.google.cn/?hl=zh-cn");
            }
        });
    }

    @Override
    public int getItemCount () {
        return items.size();
    }

    public static class MsgTypeVh extends RecyclerView.ViewHolder {
        ItemMsgTypeBinding binding;

        public MsgTypeVh (@NonNull ItemMsgTypeBinding pBinding) {
            super(pBinding.getRoot());
            binding = pBinding;
        }
    }
}
